// 云函数入口文件
const cloud = require('wx-server-sdk')
function formatTime(date) {
  const year = date.getFullYear()
  const month = '0' + (date.getMonth() + 1)
  const day = '0' + date.getDate()
  const hour = '0' + date.getHours()
  const minute = '0' + date.getMinutes()
  // const second = '0' + date.getSeconds()
  
  return `${year}年${month.slice(-2)}月${day.slice(-2)}日 ${hour.slice(-2)}:${minute.slice(-2)}`
}
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

async function get(id) {
  const db = cloud.database()
  return db.collection('flow').doc(id).get()
}

async function list({from, to, status, page, size}) {
  const skip = (page - 1) * size
  const db = cloud.database()
  const _ = db.command
  const chain = [
    {isValid: 1,}
  ]
  if (from) {
    chain.push({
      'from.openid': from
    })
  } 
  if (to) {
    chain.push({
      'to.openid': to
    })
  }
  if (status) {
    chain.push({
      status: Array.isArray(status) ? _.in(status) : status
    })
  }
  return db.collection('flow').where(_.and(chain))
  .orderBy('updatedTime', 'desc')
  .skip(skip)
  .limit(size)
  .get()
}

async function insert(data) {
  const { OPENID } = cloud.getWXContext()
  const db = cloud.database()
  const _ = db.command
  return db.collection('flow').add({
    data: {
      ...data,
      openid: OPENID,
      session: [],
      createdTime: db.serverDate(),
      updatedTime: db.serverDate(),
      isValid: 1, // 逻辑删除
      status: 10, //  10 已发起，20 已接受， 30 已结束， 40 已拒绝
    }
  })
  .then(res => {
    cloud.openapi.subscribeMessage.send({
      touser: data.to.openid,
      template_id: 'AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ',
      page: 'packageInteract/pages/detail/index?id=' + res._id,
      data: {
        thing1: {
          value: data.from.nickName,
        },
        thing2: {
          value: data.content,
        },
        time3: {
          value: formatTime(new Date()),
        },
        thing7: {
          value: data.post.title,
        },
        thing6: {
          value: '你有新的流程待处理',
        },
      }
    })
    return {code: 0, msg: 'success'}
  })
}
async function update(data) {
  const { OPENID } = cloud.getWXContext()
  const db = cloud.database()
  const { _id, from, to, ...rest} = data
  return db.collection('flow').doc(_id).update({
    data:{
      ...rest,
      updatedTime: db.serverDate(),
    }
  })
  .then(res => {
    if (rest.status) {
      cloud.openapi.subscribeMessage.send({
        touser: OPENID === from.openid ? to.openid : from.openid,
        template_id: 'AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ',
        page: 'packageInteract/pages/detail/index?id=' + _id,
        data: {
          thing1: {
            value: from.openid === OPENID ? from.nickName : to.nickName,
          },
          thing2: {
            value: {10: '已创建', 20: '已处理', 30: '完成', 40: '已拒绝'}[rest.status],
          },
          time3: {
            value: formatTime(new Date()),
          },
          thing7: {
            value: '互动状态变更',
          },
          thing6: {
            value: '你有新的消息',
          },
        }
      })
    }
    return {code: 0, msg: 'success'}
  })
}

async function comment(data) {
  const db = cloud.database()
  const _ = db.command
  const { _id, to, ...rest} = data

  return db.collection('flow').doc(_id).update({
    data:{
      session: _.push([{
        ...rest,
        createdTime: db.serverDate(),
      }]),
    }
  })
  .then(() => {
    cloud.openapi.subscribeMessage.send({
      touser: to,
      template_id: 'AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ',
      page: 'packageInteract/pages/detail/index?id=' + rest._id,
      data: {
        thing1: {
          value: rest.nickName,
        },
        thing2: {
          value: rest.content,
        },
        time3: {
          value: formatTime(new Date()),
        },
        thing7: {
          value: '留言',
        },
        thing6: {
          value: '你有新的消息',
        },
      }
    })
    return {code: 0, msg: 'success'}
  })
}

async function remove(id) {
  const db = cloud.database()
  return db.collection('flow').doc(id).remove()
}
// 云函数入口函数
exports.main = async ({action, data}) => {
 
  const func = {
    get,
    list,
    insert,
    update,
    comment,
    remove,
  }[action]
  if (func) return func(data)
}
